import java.util.concurrent.BlockingQueue;

public class Repair implements Runnable {
	
	BlockingQueue<Message> queue;

	public Repair(BlockingQueue<Message> q) {
		this.queue = q;
		new Thread(this, "Repair").start();
		System.out.println("Repairing: " + q);
	}
	
	@Override
	public void run() {
		try {
			ResponseMessage r = null;
			KeyValuePair kvp = null;
					
			do {
				r = (ResponseMessage) queue.take();
				kvp = r.getTuple();
			} while (kvp == null);
			
			for (int i = 1; i < Configuration.getInstance().getNumOfServers()-1; i++) {
				r = (ResponseMessage) queue.take();
				System.out.println("kvp:"+kvp);
				System.out.println("r:"+r);
				if (r == null) {
					System.err.println("Repair class retrieved null ResonseMessage from queue");
					continue;
				} else if (kvp.getTime().before(r.getTuple().getTime())) {
					kvp = r.getTuple();
				}
			}
			
			if (Server.localCommand(kvp, Server.REPAIR_COMMAND) == null) {
				System.err.println("Repair returned failure");
			} else {
				System.out.println("Repair completed");
			}
			
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
